﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using Website.Logger;
using DAL;
using BOL;
using System.Web.Script.Services;
using System.Web.Services;
using WebLib;
using UtilityExtensions;

namespace UILGestion.Admin.Almacenes
{
    public partial class AlmacenInsertForm : System.Web.UI.Page
    {
            [WebMethod(), ScriptMethod()]
        public static string GetEmpleado(String prefixText, String contextKey)
        {
            EmpleadoBL bol = new EmpleadoBL();
            return bol.getEmpleadoAll(prefixText, 20);
        }


        

        private void LoadAlmacen(int idAlmacen)
        {

            
            var info = DbUtil.Db.Almacens.Single(p=>p.idInternal==idAlmacen);

            idLabel.Text=info.idInternal.ToString();
            descripcionTextBox.Text=info.descripcion;
            
            responsableTextBox.Text=info.Empleado.descripcion;
            responsable1TextBox.Text=info.Empleado.descripcion;

            idResponsableTextBox.Text=info.idResponsable.ToString();

            direccionTextBox.Text = info.direccion;
            
            

            
            empresaDDL.SelectedValue = info.idEmpresa.ToString();
            loadProyecto();
            proyectoDDL.SelectedValue = info.Obra.idProyecto.ToString();
            loadObra();

            obraDropDownList.SelectedValue = info.idObra.ToString();
            


            DocumentoUpdatePanel.Update();

        }
    

        private void FormatForm()
        {

            ShowAllComboBoxNew();

            
            if (type.Value == "E")
            {
              
                LoadAlmacen(int.Parse(internalid.Value));
            }

            if (type.Value == "A")
            {
                
               
               
            }
            
            
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {


                if (!Page.IsPostBack)
                {
                   
                   
                    type.Value = (string)Request.QueryString["type"];
                    internalid.Value = (string)Request.QueryString["id"];
                   // menuObraCtrl1.loadMenu(int.Parse(idObra.Value));
                    menuCtrl1.loadMenuSeguridad();
                    FormatForm();

               

                }


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        //private void setEstadistica()
        //{
        //    List<view_ComparativoItem> itemList=
        //        (List<view_ComparativoItem>)Session[idobjectdsLabel.Value];



        //    if (itemList.Count() > 0)
        //        {
        //            totalBaseTextBox.Text = itemList.Sum(p => p.totalComparar).ToString();
        //            totalBaseTextBox.Text = itemList.ElementAt(0).simbolBase.ToString() + " " + totalBaseTextBox.Text;
        //            totalComparativoLabel.Text = itemList.Sum(p => p.totalBaseOrig).ToString();
        //            totalComparativoLabel.Text = itemList.ElementAt(0).simbolBase.ToString() + " " + itemList.Sum(p => p.totalBaseOrig).ToString();
        //        using (dbGestionDataContext _db = new dbGestionDataContext(Parametros.strConnString))
        //        {
        //            EstructuraCosto ec = _db.EstructuraCosto.Single(p => p.idInternal == int.Parse(idEstructuraCosto.Value));

        //            estructuraCostoLabel.Text = ec.descripcion;
        //            descripcionInsertTextBox.Text = ec.descripcion;

        //        }

        //    }

          
        //    CabeceraUpdatePanel.Update();
            
        //}
    
        private void ShowAllComboBoxNew()
        {
            //int idEmpresa = (int)Session["login.Empresa.idEmpresa"];
            ListValueBL bol = new ListValueBL();


            empresaDDL.DataTextField = "descripcion";
            empresaDDL.DataValueField = "idInternal";

            empresaDDL.DataSource = DbUtil.Db.Empresas;
            empresaDDL.DataBind();

            proyectoDDL.DataTextField = "descripcion";
            proyectoDDL.DataValueField = "idInternal";
            loadProyecto();
            

            obraDropDownList.DataTextField = "descripcion";
            obraDropDownList.DataValueField = "idInternal";
            loadObra();
            
        }






        protected void btnContinue_OnClick(object sender, EventArgs e)
        {
         

            try
            {
                if ((sender as Button).Text == refreshButton.Text)
                {
                    type.Value = (string)Request.QueryString["type"];
                    internalid.Value = (string)Request.QueryString["id"];
                    Response.Redirect("AlmacenInsertForm.aspx?type={0}id={1}".Fmt(type.Value,internalid.Value), false);
                }

                if ((sender as Button).Text == saveButton.Text)
                    {
                   
                        if (type.Value == "E")
                        {

                            Edit();
                        }
                        if (type.Value == "A")
                        {
                            Insert();
                        }
                

                            if (internalid.Value!="")
                            {
                    
                                // ejecutar un script 
                             //   Response.Write("javascript:history.back();");
                             //   ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                             //"uniqueKey" + DateTime.Now, "javascript:history.back();", true);
                                Response.Redirect("AlmacenReadForm.aspx?id=" + internalid.Value, false);
                            }         


            }
                if ((sender as Button).Text == cancelarButton.Text)
            {
                Response.Redirect("AlmacenListForm.aspx");
            }
           

              
                   }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);
                saveButton.Enabled = true;

            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);
                saveButton.Enabled = true;
            }
        }

        private void Insert()
        {
                System.IFormatProvider MiFp =new System.Globalization.CultureInfo("es-ES", false);
                int? idObra = int.Parse(obraDropDownList.SelectedValue);
                if (idObra == 0)
                {
                    idObra = null;
                }

                
                AlmacenBL recep = new AlmacenBL();
                int id=recep.Add(descripcionTextBox.Text,
                                int.Parse(idResponsableTextBox.Text),
                                direccionTextBox.Text,
                                idObra,
                                empresaDDL.SelectedValue.ToInt());
            internalid.Value =id.ToString();
        }

        private void Edit()
        {
            System.IFormatProvider MiFp = new System.Globalization.CultureInfo("es-ES", false);
                AlmacenBL recep= new AlmacenBL();

               
                                recep.Update(
                                    int.Parse(internalid.Value),
                                    descripcionTextBox.Text,
                                    int.Parse(idResponsableTextBox.Text),
                                    direccionTextBox.Text,
                                    int.Parse(obraDropDownList.SelectedValue),
                                    empresaDDL.SelectedValue.ToInt());

        }

        private void loadProyecto()
        {
            proyectoDDL.DataSource = new ListValueBL().GetProyectoComprasXEmpresa(empresaDDL.SelectedValue.ToInt());
            proyectoDDL.DataBind();

        }

        private void loadObra()
        {

            obraDropDownList.DataSource = new ListValueBL().GetObrasXProyecto(proyectoDDL.SelectedValue.ToInt());
            obraDropDownList.DataBind();

        }
        protected void empresaDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                loadProyecto();
                loadObra();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);
                saveButton.Enabled = true;

            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);
                saveButton.Enabled = true;
            }
        }

        protected void proyectoDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                loadObra();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);
                saveButton.Enabled = true;

            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);
                saveButton.Enabled = true;
            }
        }
   
    }

}
